from fastapi import FastAPI, File, UploadFile, HTTPException
from openpyxl import load_workbook
from methods import column_index_to_letter, list_files_in_dir
from fastapi.middleware.cors import CORSMiddleware
from shutil import copyfileobj

app = FastAPI()

# 设置CORS
origins = [
    "http://127.0.0.1:5173",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


@app.get("/file")
async def get_file():
    return {'files': list_files_in_dir('data')}


@app.get("/file/{name}")
async def get_asin(name: str):
    file_path = f'data/{name}'
    # 加载工作簿
    wb = load_workbook(file_path)

    # 获取所有工作表的名称
    sheet_names = wb.sheetnames

    asin_list = []

    # 打印工作表名称
    for sheet_name in sheet_names:
        asin_list.append(sheet_name)
    return {"message": f"Hello hjk", "data": asin_list}


@app.get("/asin/{asin}")
async def get_data_by_asin(asin: str):
    file_path = 'data/GelPolish-父ASIN销量数据-2023年.xlsx'
    wb = load_workbook(file_path)
    sheet = wb[asin]
    # 初始化最大行号为0
    max_row_with_data = 0
    max_col_with_data = 0
    # 遍历工作表的每一行
    for row in sheet.iter_rows(min_row=1, max_col=1, values_only=True):
        # row 是一个元组，其中只包含第一列的值（因为我们设置了max_col=1）
        # 如果这一行有数据（即第一个单元格不为None或空字符串等），则更新max_row_with_data
        max_row_with_data += 1
    for col in range(sheet.max_column, 0, -1):
        # 检查当前列是否有数据
        # 这里我们检查第一行的单元格，但你可能需要根据实际情况调整
        if sheet.cell(row=2, column=col).value is not None:
            max_col_with_data = col
            break
    # x轴
    x = []
    for i in range(5, max_col_with_data):
        x.append(sheet[f'{column_index_to_letter(i)}2'].value)
    # 颜色
    legend = []
    series = []
    for i in range(3, max_row_with_data):
        legend.append(sheet[f'B{i}'].value)
        obj = {
            "name": sheet[f'B{i}'].value,
            "type": 'line',
            "stack": 'Total',
            "data": []
        }
        for j in range(5, max_col_with_data):
            obj['data'].append(
                sheet[f'{column_index_to_letter(j)}{i}'].value if sheet[f'{column_index_to_letter(j)}{i}'].value else 0)
        series.append(obj)
    return {"message": f'{asin}', "data": {"x": x, 'legend': legend, 'series': series}}


# @app.post("/uploadfile/")
# async def upload_excel_file(file: UploadFile = File(...)):
#     print(file.filename)
#     # 获取文件列表，查看有无重名
#     files = list_files_in_dir('data')
#     if file.filename in files:
#         raise HTTPException(status_code=400, detail="文件名重复")
#     try:
#         # 生成文件路径
#         file_path = f'data/{file.filename}'
#         # 保存文件
#         # 使用shutil.copyfileobj()来高效地复制文件内容
#         with open(file_path, 'wb') as buffer:
#         # 注意：这里不需要显式迭代file.file，copyfileobj会处理它
#         await copyfileobj(file.file, buffer)
#
#     except Exception as e:
#         print(e)
#         raise HTTPException(status_code=400, detail=f"{e}")
#     return {'message': 'success'}
